// ScreenshotCommand.java
package org.zjx.command.basic;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.zjx.command.Command;
import org.zjx.command.CommandFactory;
import org.zjx.core.IWindow;
import org.zjx.core.impl.StartWindow;
import org.zjx.manager.ActivationManager;
import org.zjx.util.HwndUtil;
import org.zjx.util.ImageUtil;
import org.zjx.util.RobotUtil;
import org.zjx.util.WindowCaptureUtil;

import java.awt.image.BufferedImage;

/**
 * 截图指令 - 整改版本
 */
@Slf4j
public class ScreenshotCommand extends Command {
    @Getter
    private BufferedImage screenshot;

    public ScreenshotCommand(IWindow window) {
        super(window, false, null); // 截图命令自己管理激活，不依赖基类
    }

    @Override
    protected void doExecute() throws Exception {
        log.debug("[截图命令] 开始截图: {}", getTargetWindow().getId());

        // 根据窗口类型选择截图方式
        if (getTargetWindow() instanceof StartWindow) {
            // StartWindow 使用 Robot 截图（需要激活窗口）
            screenshot = captureWithRobot();
        } else {
            // 其他窗口使用 WindowCaptureUtil（不需要激活窗口）
            screenshot = captureWithWindowCapture();
        }

        this.screenshot = ImageUtil.cutImage(screenshot,targetWindow.getTrueBounds());

        log.debug("[截图命令] 截图成功: {}x{}, 窗口={}",
                screenshot.getWidth(), screenshot.getHeight(), getTargetWindow().getId());

    }

    /**
     * 使用 Robot 截图（需要激活窗口）
     */
    private BufferedImage captureWithRobot() {
        boolean activationAcquired = false;

        try {
            // 获取窗口边界（屏幕坐标）
            java.awt.Rectangle bounds = getTargetWindow().getBounds();
            if (bounds.width <= 0 || bounds.height <= 0) {
                throw new RuntimeException("窗口尺寸无效: " + bounds);
            }

            // Robot 截图需要激活窗口
            activationAcquired = ActivationManager.requestActivation(getTargetWindow());
            if (!activationAcquired) {
                throw new RuntimeException("获取窗口激活权失败，无法使用Robot截图");
            }

            // 前置窗口确保可见
            HwndUtil.preposition(getTargetWindow().getHwnd());

            // 短暂等待窗口渲染
            CommandFactory.waitDirectly(targetWindow, 50);

            log.debug("[截图命令] 使用Robot截图: {} [{}]", getTargetWindow().getId(), bounds);
            BufferedImage image = RobotUtil.getInstance().getImage(bounds);

            if (image == null) {
                throw new RuntimeException("Robot截图返回null");
            }

            return image;

        } finally {
            // 确保释放激活权（如果获取了的话）
            if (activationAcquired) {
                ActivationManager.releaseActivation(getTargetWindow());
                log.debug("[截图命令] 释放激活权: {}", getTargetWindow().getId());
            }
        }
    }

    /**
     * 使用 WindowCaptureUtil 截图（不需要激活窗口）
     */
    private BufferedImage captureWithWindowCapture() {
        try {
            if (getTargetWindow().getHwnd() == null) {
                throw new RuntimeException("窗口句柄为 null");
            }

            log.debug("[截图命令] 使用WindowCaptureUtil截图: {}", getTargetWindow().getId());
            BufferedImage image = WindowCaptureUtil.getInstance().captureWindow(getTargetWindow().getHwnd());

            if (image == null) {
                throw new RuntimeException("WindowCaptureUtil返回 null");
            }

            return image;

        } catch (Exception e) {
            log.warn("[截图命令] WindowCaptureUtil截图失败: {}", e.getMessage());
            throw new RuntimeException("WindowCaptureUtil截图失败: " + e.getMessage(), e);
        }
    }

    @Override
    public String getCommandName() {
        return "ScreenshotCommand";
    }
}